package com.dingyx.ps.filter;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author dingyuxin
 * 增加输出日志traceRootId
 */
@Slf4j
@Component
@WebFilter(filterName = "traceIdFilter",urlPatterns = "/*")
public class LogbackFilter implements Filter {

	private static final String UNIQUE_ID = "traceRootId";

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String traceId = req.getHeader("REQUEST_ID");
		boolean bInsertMDC = insertMDC(traceId);
		try {
			chain.doFilter(request, response);
		} finally {
			if(bInsertMDC) {
				MDC.remove(UNIQUE_ID);
			}
		}
	}

	private boolean insertMDC(String traceId) {
		String uniqueId = StrUtil.isNotBlank(traceId) ? traceId : IdUtil.simpleUUID();
		MDC.put(UNIQUE_ID, uniqueId);
		return true;
	}

	@Override
	public void destroy() {

	}

}
